package org.tinygroup.channel.protocol.impl;

import java.util.List;

import org.tinygroup.channel.protocol.ChannelClient;
import org.tinygroup.channel.protocol.ProtocolListener;
import org.tinygroup.channel.protocol.ProtocolOutInterface;
import org.tinygroup.context.Context;
import org.tinygroup.context.util.ContextFactory;

public class BaseProtocolOut<Request, Response> extends
		AbstractProtocolInterface implements
		ProtocolOutInterface<Request, Response> {
	private ChannelClient channelClient;
	

	public Response send(Request req) {
		List<ProtocolListener<?, ?>> listeners = getListeners();
		ProtocolListenerChain chain = new ProtocolListenerChain(listeners);
		Context context = ContextFactory.getContext();
		chain.pre(req, context);
		Object requestMessage = getProtocolTrans().transReqToMessage(req, context);
		Object responseMessage = (Response) channelClient.send(requestMessage);
		chain.post(req, responseMessage, context);
		return (Response) getProtocolTrans().transRespFromMessage(responseMessage, context);
	}

	public void asynSend(Request req) {
		List<ProtocolListener<?, ?>> listeners = getListeners();
		ProtocolListenerChain chain = new ProtocolListenerChain(listeners);
		Context context = ContextFactory.getContext();
		chain.pre(req, context);
		Object requestMessage = getProtocolTrans().transReqToMessage(req, context);
		channelClient.asynSend(requestMessage);
		chain.post(req, null, context);
	}

	public void setChannelClient(ChannelClient client) {
		this.channelClient = client;
	}

	public ChannelClient getChannelClient() {
		return channelClient;
	}
	
}
